package dinamico.persistencia.controller;

import dinamico.persistencia.entities.Zona;
import java.util.List;
import javax.persistence.EntityManager;


public class ZonaController
{
   private EntityManager entityManager;

    public ZonaController (EntityManager entityManager)
    {
        this.entityManager = entityManager;
    }

    public Zona findZonaByid(int codZona) throws Exception
    {
        Zona user = new Zona();
        try
        {
            javax.persistence.Query query = entityManager.createQuery
                ("select c from zona as c where c.id = " + codZona);
            user =  (Zona) query.getSingleResult();
            return user;
        }
        catch(Exception ex)
        {
            ex.fillInStackTrace();
            return null;
        }
    }

  public List<Zona> getAllZona() throws Exception
  {
    try
    {
        javax.persistence.Query query = entityManager.createQuery
            ("select c from Zona as c");
        return query.getResultList();
    }
    catch(Exception ex)
    {
          ex.printStackTrace();
          throw ex;
    }
  }

    public boolean deleteZona(int id) throws Exception
    {
        try
        {
            entityManager.getTransaction().begin();
            Zona zonaToDelete =
                    entityManager.find(Zona.class, id);
            entityManager.remove(zonaToDelete);
            entityManager.getTransaction().commit();
            return true;
        }
        catch (Exception ex)
        {
            if (entityManager.getTransaction().isActive())
            {
                entityManager.getTransaction().rollback();
            }
            return false;
        }
    }



    public boolean insertZona(Zona zona) throws Exception
    {
        try
        {
            entityManager.getTransaction().begin();
            entityManager.persist(zona);
            entityManager.getTransaction().commit();
            return true;
        }
        catch(Exception ex)
        {
           if (entityManager.getTransaction().isActive())
           {
                entityManager.getTransaction().rollback();
           }
           ex.printStackTrace();
           return false;
        }
    }

    public Zona findZonaByName(String nombre) throws Exception
    {
        Zona zona = new Zona();
        try
        {
            javax.persistence.Query query = entityManager.createQuery
                ("select c from Zona as c where c.nombre = " + nombre);
            zona =  (Zona) query.getSingleResult();
            return zona;
        }
        catch(Exception ex)
        {
            ex.fillInStackTrace();
            return null;
        }
    }

}
